<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">


      <el-form-item label="优惠券类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable size="small" style="width:120px;">
          <el-option label="全部" value="" />
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="优惠券名称" prop="name">
        <el-input
          v-model="queryParams.name" style="width:150px;"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable size="small" style="width:150px;"
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="截至时间" prop="endTime">
        <el-date-picker clearable size="small" style="width:150px;"
          v-model="queryParams.endTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择截至时间">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small" style="width:120px;">
          <el-option label="全部" value="" />
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="限制区域" prop="areaCode">
        <el-input
          v-model="queryParams.areaCode"
          placeholder="请输入限制区域"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:coupon:add']"
        >新增</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-tabs  v-model="tabActiveName" @tab-click="handleTabClick">
        <el-tab-pane label="全部" name="all"></el-tab-pane>
        <el-tab-pane  v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel" :name="dict.dictValue"></el-tab-pane>
    </el-tabs>

    <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="类型" align="left" prop="type" >
        <template slot-scope="scope">
          {{selectDictLabel(typeOptions, scope.row.type)}}
        </template>
      </el-table-column>
      <el-table-column label="优惠方式" align="left" prop="dtype" >
        <template slot-scope="scope">
          {{selectDictLabel(dtypeOptions, scope.row.dtype)}}
        </template>
      </el-table-column>
      <el-table-column label="名称" align="left" prop="name"  width="200" />
      <!-- <el-table-column label="标签" align="left" prop="tag" /> -->
      <el-table-column label="总数量" align="center" prop="total" />
      <el-table-column label="已发放数" align="center" prop="hasCount" />
      <el-table-column label="金额/折扣" align="center" prop="discount" >
        <template slot-scope="scope">
          {{scope.row.dtype == 1 ? '￥' + scope.row.discount : scope.row.discount + '%'}}
        </template>
      </el-table-column>
      <el-table-column label="最少消费" align="center" prop="min" />
      <el-table-column label="最高抵扣" align="center" prop="max" />
      <el-table-column label="限制数量" align="center" prop="limits" />
      <!-- <el-table-column label="有效天数" align="center" prop="days" /> -->
      <el-table-column label="开始时间" align="center" prop="startTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="截至时间" align="center" prop="endTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="限制类目" align="center" prop="cateType" /> -->
      <!-- <el-table-column label="限制区域" align="center" prop="areaCode" /> -->
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          {{selectDictLabel(statusOptions, scope.row.status)}}
        </template>
      </el-table-column>
      <el-table-column label="分享" align="center" prop="share" >
        <template slot-scope="scope">
          {{selectDictLabel(shareOptions, scope.row.share)}}
        </template>
      </el-table-column>
      <!-- <el-table-column label="兑换码" align="center" prop="code" /> -->
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-bottom"
            @click="handleSoldOut(scope.row)"
          >下架</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handleGive(scope.row)"
          >发放</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠券管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="优惠券类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择优惠券类型">
                <el-option
                v-for="dict in typeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优惠方式" prop="dtype">
              <el-select v-model="form.dtype" placeholder="请选择优惠方式">
                <el-option
                v-for="dict in dtypeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="优惠券名" prop="name">
              <el-input v-model="form.name" placeholder="请输入优惠券名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="介绍" prop="descr">
              <el-input v-model="descr" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标签" prop="tag" >
              <el-input v-model="form.tag" placeholder="请输入优惠券标签，例如新人专用" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否分享" prop="share">
              <el-radio v-model="form.share" label="1">是</el-radio>
              <el-radio v-model="form.share" label="0">否</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="14">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="折扣%" prop="discount" v-if="form.dtype == 2">
                  <el-input v-model="form.discount" placeholder="请输入折扣，0~100" />
                </el-form-item>
                <el-form-item label="金额" prop="discount" v-else>
                  <el-input v-model="form.discount" placeholder="请输入优惠金额" />
                </el-form-item>
                
              </el-col>
              <el-col :span="8">
                <el-form-item label="数量" prop="total">
                  <el-input v-model="form.total" placeholder="请输入优惠券数量，如果是0，则是无限量" />
                </el-form-item>
              </el-col>
            </el-row>
             <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="最高抵扣" prop="max" v-if="form.dtype == 2">
                  <el-input v-model="form.max" placeholder="请输入优惠券最高抵扣金额。" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="最少金额" prop="min">
                  <el-input v-model="form.min" placeholder="请输入最少消费金额才能使用优惠券。" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="限制数量" prop="limits">
                  <el-input v-model="form.limits" placeholder="请输入用户领券限制数量" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="开始时间" prop="startTime">
                  <el-date-picker clearable size="small"
                    v-model="form.startTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择使用券开始时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="截至时间" prop="endTime">
                  <el-date-picker clearable size="small"
                    v-model="form.endTime"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择使用券截至时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="10" v-if="form.type && form.type == 1">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="限制类目" prop="cateType" size="mini"  >
                  <treeselect v-model="form.cateType" :multiple="false" :options="categoryOptions"
                    @select="selectTypeChange" :normalizer="normalizer" placeholder="请选择类目"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>


        <!-- <el-row :gutter="20">
          <el-col :span="12">
             <el-form-item label="有效时间" prop="timeType">
              <el-select v-model="form.timeType" placeholder="请选择有效时间限制，如果是0，则基于领取时间的有效天数days；如果是1，则start_time和end_time是优惠券有效期；">
                <el-option label="请选择字典生成" value="" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效天数" prop="days">
              <el-input v-model="form.days" placeholder="请输入基于领取时间的有效天数days。" />
            </el-form-item>
          </el-col>
        </el-row> -->


        <!-- <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="限制区域" prop="areaCode">
              <el-input v-model="form.areaCode" placeholder="请输入限制区域" />
            </el-form-item>
          </el-col>
        </el-row> -->
        <!-- <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="兑换码" prop="code">
              <el-input v-model="form.code" placeholder="请输入优惠券兑换码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">

          </el-col>
        </el-row> -->
        <el-row :gutter="20">
          <el-col :span="24"  v-if="form.type && form.type == 1">
            <el-tabs >

              <el-tab-pane label="限制服务" >
                <el-button type="primary" @click="selectAttrList">选择服务</el-button>
                <el-table  :data="attributeList" max-height="200" >
                  <el-table-column label="编号" align="center" prop="id" />
                  <el-table-column label="项目名称" align="left" prop="name" width="250" show-overflow-tooltip/>
                  <el-table-column label="单位" align="center" prop="unit" />

                  <el-table-column label="指导价" align="center" prop="price" />
                  <!-- <el-table-column label="指导价浮动" align="center" prop="floatPrice" /> -->
                  <el-table-column label="下单价" align="center" prop="costPrice" />
                  <!-- <el-table-column label="下单价浮动" align="center" prop="costFloatPrice" /> -->
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="handleAttrDelete(scope.row)"
                    >删除</el-button>
                  </template>
                </el-table-column>

                </el-table>
              </el-tab-pane>
              <el-tab-pane label="限制区域" ></el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <select-item ref="selectItem" v-if="itemOpen"  @finishSelected="finishSelectItem" ></select-item>
    </el-dialog>


    <!-- 下发优惠券管理对话框 -->
    <el-dialog title="发放优惠券" :visible.sync="giveOpen" width="55%" append-to-body>
      <el-tabs >
        <el-tab-pane label="手动发放">
          <el-row :gutter="20">
            <!--用户数据-->
            <el-col :span="24" >
              <el-form :model="userQueryParams" ref="queryUserForm" :inline="true" v-show="showSearch1" label-width="68px">
                <el-form-item label="用户账号" prop="userName">
                  <el-input
                    v-model="userQueryParams.userName"
                    placeholder="请输入用户账号"
                    clearable
                    size="small"
                    style="width: 240px"
                    @keyup.enter.native="handleUserQuery"
                  />
                </el-form-item>
                <el-form-item label="用户昵称" prop="nickName">
                  <el-input
                    v-model="userQueryParams.nickName"
                    placeholder="请输入用户昵称"
                    clearable
                    size="small"
                    style="width: 240px"
                    @keyup.enter.native="handleUserQuery"
                  />
                </el-form-item>
                <el-form-item label="手机号码" prop="phonenumber">
                  <el-input
                    v-model="userQueryParams.phonenumber"
                    placeholder="请输入手机号码"
                    clearable
                    size="small"
                    style="width: 240px"
                    @keyup.enter.native="handleUserQuery"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="el-icon-search" size="mini" @click="handleUserQuery">搜索</el-button>
                  <el-button icon="el-icon-refresh" size="mini" @click="resetUserQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
          <el-table v-loading="uloading" :data="userList" style="width: 100%" height="400">
            <el-table-column type="selection" width="50" align="center"  />
            <el-table-column label="头像" align="center" key="avatar" prop="avatar" >
              <template slot-scope="scope">
                <el-image v-if="scope.row.avatar"
                          style="width: 40px; height: 40px;border-radius: 50%;"
                          :src="scope.row.avatar">
                </el-image>
              </template>
            </el-table-column>
            <el-table-column label="账号" align="center" key="userName" prop="userName"   />
            <el-table-column label="名称" align="center" key="nickName" prop="nickName"  />
            <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber"  />
            <el-table-column label="注册时间" align="center" prop="createTime"  width="160"/>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-s-promotion"
                  @click="submitGive(scope.row)"
                >发放</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total>0"
            :total="userTotal"
            :page.sync="userQueryParams.pageNum"
            :limit.sync="userQueryParams.pageSize"
            @pagination="getUserList"
          />


        </el-tab-pane>
        <el-tab-pane label="生成链接">
          <el-form ref="form" :model="form"  label-width="100px" >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="优惠券类型" prop="type">
                  <el-select v-model="form.type" placeholder="请选择优惠券类型" disabled>
                    <el-option
                    v-for="dict in typeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="优惠方式" prop="dtype">
                  <el-select v-model="form.dtype" placeholder="请选择优惠方式" disabled>
                    <el-option
                    v-for="dict in dtypeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="优惠券名" prop="name">
                  <el-input v-model="form.name" placeholder="请输入优惠券名称" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="介绍" prop="descr">
                  <el-input v-model="descr" type="textarea" placeholder="请输入内容" disabled />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="折扣%" prop="discount" v-if="form.dtype == 2">
                  <el-input v-model="form.discount" placeholder="请输入折扣，0~100" disabled />
                </el-form-item>
                <el-form-item label="金额" prop="discount" v-else>
                  <el-input v-model="form.discount" placeholder="请输入优惠金额" disabled />
                </el-form-item>
                
              </el-col>
              <el-col :span="6">
                <el-form-item label="最高抵扣" prop="max" v-if="form.dtype == 2">
                  <el-input v-model="form.max" placeholder="请输入优惠券最高抵扣金额" disabled />
                </el-form-item>
              </el-col>     
              <el-col :span="6">
                <el-form-item label="最低金额" prop="min">
                  <el-input v-model="form.min" placeholder="请输入最低消费金额" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="数量" prop="total">
                  <el-input v-model="form.total" placeholder="请输入优惠券数量" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="复制链接" >
                  <el-input  type="textarea" v-model="shareLink" placeholder="请输入内容" />
                  <el-button type="primary" style="margin-top:10px;" @click="handleCopy">复制</el-button>
                </el-form-item>  
              </el-col>                
            </el-row>               

          </el-form>
        </el-tab-pane>
      </el-tabs>
      
<!--      <div slot="footer" class="dialog-footer" >-->
<!--        <template >-->
<!--          <el-button type="primary" @click="submitGive(scope.row)" >确 定</el-button>-->
<!--          <el-button @click="cancel">取 消</el-button>-->
<!--        </template>-->
<!--      </div>-->
    </el-dialog>
  </div>
</template>

<script>

import { listCoupon, getCoupon, delCoupon, addCoupon, updateCoupon, exportCoupon } from "@/api/business/coupon";
import { listCategory, getCategory } from "@/api/business/category";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import SelectItem from '@/views/business/coupon/selectItem.vue';
import {listUser} from "@/api/system/user";
import {addCouponUser} from "@/api/business/couponUser";


export default {
  name: "Coupon",
  components: {
    Treeselect,
    SelectItem
  },
  data() {
    return {

      tabActiveName: 'all',
      itemOpen: false,
      // 遮罩层
      loading: true,
      uloading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      showSearch1: true,
      // 总条数
      total: 0,
      userTotal:0,

      row1: 0,
      // 优惠券管理表格数据
      couponList: [],
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      attributeList: [],
      userCouponList:[],
      //赠送优惠券
      giveOpen: false,
      // 状态数据字典
      statusOptions: [],
      shareOptions: [],
      categoryOptions: [],
      // 类型数据字典
      typeOptions: [],
      dtypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        descr: null,
        tag: null,
        total: null,
        discount: null,
        min: null,
        limits: null,
        type: null,
        status: null,
        share: null,
        cateType: null,
        code: null,
        timeType: null,
        days: null,
        startTime: null,
        endTime: null,
        areaCode: null
      },
      userQueryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: undefined,
        userName: undefined,
        status: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        type: [
          { required: true, message: "优惠券类型不能为空", trigger: "blur" }
        ],
        dtype: [
          { required: true, message: "优惠方式不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "优惠券名称不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "截止时间不能为空", trigger: "blur" }
        ],
        cateType: [
          { required: true, message: "限制类目不能为空", trigger: "blur" }
        ],
        total: [
          { required: true, message: "优惠券数量，如果是0，则是无限量不能为空", trigger: "blur" }
        ],
      }
    };
  },

  computed: {
    // 计算属性的 getter
    descr: function () {
      // `this` 指向 vm 实例
      // return this.message.split('').reverse().join('')
      if (this.form.dtype == 1) {
        return "满" + this.form.min+ "元减" +this.form.discount + "元"
      } else {
        return "满" + this.form.min+ "元打" + (this.form.discount/10).toFixed(1) + "折"
      }
      
    },
    shareLink: function() {
      let h5Url = process.env.VUE_APP_DOMAIN_NAME + "/h5/tiao.html?id=" + this.form.id;
      return "送你一张" + this.descr + "的优惠券，请点击链接立即领取：" + h5Url;
    }
  },

  created() {
    this.getList();
    this.getUserList();
    this.getDicts("tb_coupon_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("tb_coupon_share").then(response => {
      this.shareOptions = response.data;
    });
    this.getDicts("tb_coupon_type").then(response => {
      this.typeOptions = response.data;
    });
    this.getDicts("tb_coupon_dtype").then(response => {
      this.dtypeOptions = response.data;
    });
    this.getTreeselect();
  },
  methods: {
    /** 查询优惠券管理列表 */
    getList() {
      this.loading = true;
      listCoupon(this.queryParams).then(response => {
        this.couponList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleCopy(){
      this.copy(this.shareLink)
    },
    copy(data){
      let url = data;
      let oInput = document.createElement('input');
      oInput.value = url;
      document.body.appendChild(oInput);
      oInput.select(); // 选择对象;
      document.execCommand("Copy"); // 执行浏览器复制命令
      oInput.remove()
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.giveOpen = false;
      this.reset();
    },
    /** 搜索按钮操作 */
    handleUserQuery() {
      this.userQueryParams.page = 1;
      this.userQueryParams.status = 0;
      this.getUserList();
    },
    /** 重置按钮操作 */
    resetUserQuery() {
      this.resetForm("queryUserForm");
      this.handleUserQuery();
    },
    /** 查询用户列表 */
    getUserList() {
      this.uloading = true;
      listUser(this.userQueryParams).then(response => {
          this.userList = response.rows;
          this.userTotal = response.total;
          this.uloading = false;
        }
      );
    },
    submitGive(row){
      const data ={}
      data.userId = row.userId
      data.couponId = this.row1.id
      data.userName = row.nickName
      console.log(data)
      addCouponUser(data).then(response => {
        this.msgSuccess("下发成功");
      })
    },
    handleTabClick(tab, event){
      if (tab.name != 'all') {
        this.queryParams.status = tab.name;
      }else{
        this.queryParams.status = '';
      }
      this.getList();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        tag: null,
        total: null,
        discount: 5,
        min: 50,
        limits: 1,
        type: null,
        status: 0,
        cateType: null,
        descr: null,
        code: null,
        timeType: null,
        days: null,
        startTime: null,
        endTime: null,
        createTime: null,
        areaCode: null
      };
      this.resetForm("form");
      this.attributeList = [];
    },
    /** 查询服务类目下拉树结构 */
    getTreeselect() {
      listCategory().then(response => {
        this.categoryOptions = [];
        const data = { id: 0, name: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.categoryOptions.push(data);
      });
    },
    /** 转换服务类目数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    selectTypeChange(node, instanceId) {
      debugger
      if (node.id != this.form.cateType) {
        this.attributeList = [];
      }
    },
    selectAttrList() {
      if (!this.form.cateType) {
        this.msgError("请先选择限制类目");
        return;
      }
      this.itemOpen = true;
      this.$nextTick(()=>{
        this.$refs['selectItem'].init(this.form.cateType);
      });
    },
    finishSelectItem(list) {
      this.attributeList = this.attributeList.concat(list);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    selectUserChange(selection){
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
      console.log(this.ids)
      console.log(this.single)
      console.log(this.multiple)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加优惠券管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCoupon(id).then(response => {
        this.form = response.data;
        this.form.type = this.form.type + "";
        this.form.dtype = this.form.dtype + "";
        this.form.share = this.form.share + "";
        if (this.form.attributeList) {
          this.attributeList = this.form.attributeList;
        }
        this.open = true;
        this.title = "修改优惠券管理";
      });
    },
    handleGive(row){
      this.row1 =row;
      console.log(this.row1)
      const id = row.id || this.ids
      this.giveOpen=true;
      //
      getCoupon(id).then(response => {
        this.form = response.data;
        this.form.type = this.form.type + "";
        this.form.dtype = this.form.dtype + "";
      });
    },

    handleSoldOut(row){
      console.log(row)
      this.$confirm('此操作将下架该优惠券, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.status=2
        console.log(row)
        updateCoupon(row).then(response => {
          this.msgSuccess("下架成功");
          this.getList();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消下架'
        });
      });
    },
    handleAttrDelete(row){
      this.attributeList = this.attributeList.filter(a=>a.id!=row.id)
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.limitItems = this.attributeList?.map(a=>a.id).join(",");
          this.form.descr = this.descr;
          if (this.form.id != null) {
            updateCoupon(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCoupon(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除优惠券管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCoupon(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有优惠券管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportCoupon(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        })
    }
  }
};
</script>
